package com.fxust.common;

import com.fxust.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;

/**
 * @auto johnking
 * @create 2017-12-17 上午11:22
 **/
public class PropertiesHandler {

    private static final Logger logger = LoggerFactory.getLogger(PropertiesHandler.class);

    private static String    filePath    = FileUtils.getDataSourcePropertiesFilePath();

    public static Properties loadPropertiesConfig() {
        Properties prop = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            prop.load(inputStream);
        } catch (Exception e) {
            logger.error("读取配置文件出错", e);
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                logger.error("关闭输入流错误",e);
            }
        }
        return prop;
    }

    public static String readPropertiesConfigByKey(String key) {
        Properties prop = new Properties();
        String value = null;
        try {
            InputStream inputStream = new FileInputStream(filePath);
            prop.load(inputStream);
            value = prop.getProperty(key);
            inputStream.close();
        } catch (Exception e) {
            logger.error("读取配置文件出错", e);
        }
        return value.trim();
    }

    public static String readPropertiesConfigByKey(String key,String filePath) {
        Properties prop = new Properties();
        String value = null;
        try {
            InputStream inputStream = new FileInputStream(filePath);
            prop.load(inputStream);
            value = prop.getProperty(key);
            inputStream.close();
        } catch (Exception e) {
            logger.error("读取配置文件出错", e);
        }
        return value.trim();
    }

    public static void writePropertiesInfo(String key, String value) {
        Properties prop = new Properties();
        try {
            FileInputStream in = new FileInputStream(filePath);
            prop.load(in);
            in.close();
            prop.setProperty(key, value);
            FileOutputStream out = new FileOutputStream(filePath);
            prop.store(out, "Conmments");
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error("配置文件写入取错误",e);
        }
    }
}
